package com.unittec.drainage.provider.manage.common.mybatisTypeHandler;

import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.io.WKTReader;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.postgresql.util.PGobject;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author CopySun
 * @date 2020/9/11 13:34
 */
@MappedJdbcTypes(JdbcType.OTHER)
@MappedTypes({Geometry.class})
public class ToGeomTypeHandler<T extends Geometry> extends BaseTypeHandler<T> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        PGobject pGobject = new PGobject();
        pGobject.setType("geometry");
        pGobject.setValue(parameter.toText());
        ps.setObject(i, pGobject);
    }

    @Override
    public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String wkt = (String)rs.getObject(columnName);
        return (T)getGeometryFromWkt(wkt);
    }

    @Override
    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String wkt = (String)rs.getObject(columnIndex);
        return (T)getGeometryFromWkt(wkt);
    }

    @Override
    public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String wkt = (String)cs.getObject(columnIndex);
        return (T)getGeometryFromWkt(wkt);
    }

    /**
     * 从WKT中获取几何
     *
     * @param wkt
     * @return
     */
    private Geometry getGeometryFromWkt(String wkt) {
        WKTReader reader = new WKTReader();
        Geometry geometry = null;
        try {
            geometry = reader.read(wkt);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (geometry == null) {
            return null;
        }
        return geometry;
    }
}
